<?php

namespace Kollway\Logger\Services;

use Carbon\Carbon;
use Kollway\Logger\Swagger\SwaggerService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class LoggerService
{
    // log id
    protected $id;

    public static function log(Request $request, Response $response)
    {
        // 不记录查看 log 的请求
        if (str_contains($request->getPathInfo(), '_logger')) {
            return;
        }
        $swagger_info = (new SwaggerService())->getSwaggerInfo();

        // 限制最多保存 100 条记录
        $id = \Cache::get('_log_count');
        if ($id >= 100) {
            \DB::table('logger')->delete();
            \Cache::pull('_log_count');
        }

        $id = \DB::table('logger')->insertGetId([
            'pathinfo' => $request->getPathInfo(),
            'request_header' => $request->headers,
            'request_body' => $request->getContent(),
            'response_header' => $response->headers,
            'response_body' => $response->getContent(),
            'full_url' => \Request::fullUrl(),
            'method' => $request->getMethod(),

            // 文档相关信息
            'doc_url' => $swagger_info ? $swagger_info['doc_url'] : '',
            'is_deprecated' => $swagger_info ? $swagger_info['is_deprecated'] : 0,
            'summary' => $swagger_info ? $swagger_info['summary'] : '',
            'tag' => $swagger_info ? $swagger_info['tag'] : '',

            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
        if ($id) {
            \Cache::increment('_log_count');
        }
    }
}